package hn.cch.druid.service;

import hn.cch.druid.entity.User;
import hn.cch.druid.query.Joiner;
import hn.cch.druid.query.Operator;
import hn.cch.druid.query.Where;
import hn.cch.druid.redis.UserRedis;
import hn.cch.druid.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author CCH
 * @version 2018.08.31
 */

@Service
public class UserService {


    @Autowired
    private UserRepository userRepository;
    @Autowired
    private UserRedis userRedis;

    /**
     * 条件查询：根据参数查询用户
     * @param user
     * @return
     */
    public List<User> findUser(User user){

        Where where = new Where(Joiner.AND, new ArrayList<>());

        //属性非空：拼接条件
        if (!StringUtils.isEmpty(user.getId())){
            where.add(Operator.EQ,"id", user.getId());
        }
        if (!StringUtils.isEmpty(user.getName())){
            where.add(Operator.LIKE,"name", "%"+user.getName()+"%");
        }

        return userRepository.findWhere(where);

    }


    /**
     * 缓存
     */

    @Cacheable(value = "redis:mysql:user:select", keyGenerator = "className")
    public User selectById(Long id){
        return userRepository.findOne(id);
    }

    @CachePut(value = "redis:mysql:user:insert", keyGenerator = "objectId")
    public User insertByRole(User user){
        return userRepository.save(user);
    }

    @CacheEvict(value = "redis:mysql:user:delete", keyGenerator = "className")
    public void deleteById(Long id){
        userRepository.delete(id);
    }
}
